package com.xposed.aliproxy.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.xposed.aliproxy.db.AliTradeModel;
import com.xposed.aliproxy.db.DBUtil;
import com.xposed.aliproxy.qrcode.GlobalInstance;
import com.xposed.aliproxy.thread.UploadAliTradeThread;
import com.xposed.aliproxy.utils.ActionUtil;
import com.xposed.aliproxy.utils.ToastUtil;

/**
 * 交易模式广播监听
 */
public class AliTradeModelReceiver extends BroadcastReceiver {
    private Context context;
    private DBUtil dbUtil;

    public AliTradeModelReceiver(Context context, DBUtil dBUtil) {
        this.context = context;
        this.dbUtil = dBUtil;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ActionUtil.RECEIVER_TRADE_MODEL.equals(intent.getAction())) {
            AliTradeModel aliTradeModel = (AliTradeModel) intent.getSerializableExtra("aliTradeModel");
            aliTradeModel.setAliBalance(GlobalInstance.getInstance().f1769h);
            String tradeNo = aliTradeModel.getTradeNo();
            if (intent.getBooleanExtra("isMer", false) || !this.dbUtil.queryAlitradeByTradeNo(tradeNo)) {
                if (this.dbUtil.insertAlitrade(aliTradeModel) > 0) {
                    ToastUtil.showToast(context, String.format("交易成功：金额%s,备注%s,姓名%s,余额%s",
                            new Object[]{aliTradeModel.getAmount(), aliTradeModel.getRemark(), aliTradeModel.getName(), aliTradeModel.getAliBalance()}));
                }
                new UploadAliTradeThread(context, aliTradeModel).start();
            }
        }
    }
}
